package com.xuwang.Util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTutil {
    private static String token="token!xuwangdashuaibi";


    /*
    生成token
     */
    public static String createToken(Map<String,String >map){
        final JWTCreator.Builder newBuilder = JWT.create();
        for (Map.Entry<String,String> entry : map.entrySet()) {
           newBuilder.withClaim(entry.getKey(),entry.getValue());
        }
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND,90*60);
        newBuilder.withExpiresAt(calendar.getTime());
        return newBuilder.sign(Algorithm.HMAC256(token));
    }


        /*
        验证token的合法性
         */
    public static void  verifyToken(String Token){
            JWT.require(Algorithm.HMAC256(token)).build().verify(Token);
    }
    /*
    获取token的真实值
     */
    public static DecodedJWT getToken(String Token) {
        return JWT.require(Algorithm.HMAC256(token)).build().verify(Token);

    }
    /*
     * 根据token解密，获取用户名
     */
    public static String getUserName(String token){
        DecodedJWT token1 = getToken(token);
        return token1.getClaims().get("username").asString();
    }

}
